// pages/searchEquip/searchEquip.js  
const app = getApp()
const util = require('../../utils/util.js')
const lbbService = require('../service/service.js')
const qrcode = require('../../utils/weapp.qrcode.esm.js')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    requestFlag: false,
    equipType: 1,
    batteryType: 1,
    show:true,
    qrCodeText:null,
    qrCodeLink:null,
    selGoodsList:[],
    myPartList:[],
    equipTypes: [{
      value: 1,
      name: '桩',
      checked: true
    }, {
      value: 2,
      name: 'qc码'
    }]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    that.setData({
      scrollHeight:app.getScrollHeight(0)
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    let that = this
    that.toast = that.selectComponent("#toast")
    that.personalModal = that.selectComponent("#personalModal")
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let that = this
    let equipType = that.data.equipType
    if (that.data.inputCode) {
      that.getQrcode()
    }
    
    // //添加物品
    // if (that.data.addGoodsFlag) {
    //   let list = that.data.selGoodsList
    //   that.setData({
    //     show: false,
    //   })
    //   util.print('selGoodsList',list);
    //   for (var i = 0; i < list.length; i++) {
    //     that.selGoodsAdd(list[i]);
    //   }
    //   that.data.selGoodsList = [];
    //   that.setData({
    //     show: true,
    //   })
    // }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },
  stopMaoPao: function () {
    return
  },

  /**
   * 扫码获取控制盒编号
   */
  scanBoxCode: function () {
    let that = this;
    wx.scanCode({
      success(res) {
        console.log('scanCode-->',res);
        let qrc = '';
        let qrCode = res.result;
        if(!qrCode){
          that.toast.showToast('二维码为空');
          return;
        }
        that.setData({
            qrCodeText:qrCode
        }) 
        that.getQrcode()
        // let reg = /^([A-Za-z0-9]{2}:){5}([A-Za-z0-9]{2}){1}$/;
        // if (qrCode.indexOf(util.CONST_DATA.DEVICE_QRCODE_URL_PREFIX) == 0) {
        //   //控制盒大二维码
        //   var rst = qrCode.split('/');
        //   qrc = rst[rst.length - 1];
        //   that.data.scan_qrc = qrc;
        // } else if (reg.test(qrCode)) {
        //   //控制盒小二维码
        //   that.data.deviceId = qrCode;
        //   that.data.mac = qrCode.replace(/:/g, '');
        //   lbbService.getHpIdByMacId({mac:that.data.mac},res=>{
        //     that.setData({
        //       inputCode: res.data.pileId+'',
        //     })
        //     that.search();
        //   })
        //   return;
        // } else {
        //   that.toast.showToast('二维码错误');
        //   return
        // }
        // lbbService.getMacId({
        //   markCode: that.data.scan_qrc,
        //   system:'Android'
        // }, function (res) {
        //   if (res.pileId) {
        //     that.setData({
        //       inputCode: res.pileId+'',
        //     })
        //     that.search();
        //   } else {
        //     that.toast.showToast('获取mac失败');
        //   }
        // })
      },
    })
  },
  equipTypeChange: function (e) {
    let equipType = e.detail.value
    this.setData({
      equipType:equipType
    })
  },
  inputChange: function (e) {
    let inputCode = e.detail.value
    this.setData({
      inputCode: inputCode
    })
  },
  clearInput: function () {
    this.setData({
      inputCode: ''
    })
  },
  blurEvent: function () {
    let that = this
    setTimeout(function () {
      that.setData({
        isFocus: false
      })
    }, 50)
  },
  focusEvent: function () {
    this.setData({
      isFocus: true
    })
  },
  search: function (e) {
    let that = this
    console.log('search',that.data.inputCode);
    let inputCode = that.data.inputCode.replace(/[^0-9]/ig, "");
    console.log('search1',inputCode);
    if (!inputCode) {
      that.toast.showToast('请输入编号');
      return
    }
    that.getQrcode()
  },

  getQrcode:function() {
    let that = this
    let equipType = that.data.equipType
    let equipCode = that.data.inputCode ? that.data.inputCode.replace(/[^0-9]/ig, "") : "";
    let qrCode = that.data.qrCodeText
    let data = {
        qrc:'',
        mac:'',
        hid:'',
        qrcId:''
    }
    if (equipType=='1' || equipType == 1) {
        if (qrCode) {
            data.mac = qrCode
        }
        if (equipCode) {
            data.hid = equipCode
        }
    } else {
        if (qrCode) {
            data.qrc = qrCode
        }
        if (equipCode) {
            data.qrcId = equipCode
        }
    }
    lbbService.postQrcode(data,function (res) {
        console.log(res.data)
        
        if (equipType=='1' || equipType == 1) {
            if (res.data.qrc && res.data.qrcId) {
                that.setData({
                    qrCodeLink:res.data.qrc,
                    qrContent:res.data.qrcId
                })
                that.createQrcode()
            } else {
                that.toast.showToast('未查询到关联的qc码');
                return
            }
        } else {
            if (res.data.mac && res.data.hid) {
                that.setData({
                    qrCodeLink:res.data.mac,
                    qrContent:res.data.hid
                })
                that.createQrcode()
            } else {
                that.toast.showToast('未查询到关联的mac码');
                return
            }
        }
    })
  },
//   getEquipInfo: function () {
//     let that = this
//     let equipCode = that.data.inputCode.replace(/[^0-9]/ig, "")
//     lbbService.getEquipDetailInfo({
//       equId: parseInt(equipCode)
//     }, function (res) {
//       res.data.lastOperateStatTime=util.formatTime(new Date(res.data.lastOperateStatTime))
//       res.data.lastOperateStatTime=res.data.lastOperateStatTime.replace(new RegExp("/","gm"),"-")
//       that.setData({
//         equipInfo: res.data,
//         pileInfo: {}
//       })
//     })
//   },
//   selGoodsAdd: function (selectGoods) {
//     let index = this.data.myPartList.findIndex(item=>item.id==selectGoods.id);
//     if(index>-1){
//       this.data.myPartList[index].accNum = selectGoods.accNum;
//     } else {
//       this.data.myPartList.push(selectGoods);
//     }
//     this.setData({
//       myPartList: this.data.myPartList
//     });
//     this.data.addGoodsFlag = false;
//   },
  /**
   * 清除已选择的配件
   */
//   deleteMyPartList: function(){
//     this.setData({
//       myPartList:[]
//     })
//   },
//   deleteParts: function (e) {
//     let that = this;
//     let id = e.detail;
//     console.log('deleteParts', id);
//     let myPartList = that.data.myPartList;
//     myPartList.forEach((item, index) => {
//       if (item.id == id) {
//         myPartList.splice(index, 1);
//       }
//     })
//     that.setData({
//       myPartList: myPartList
//     })
//   },
  /**
   * 获取桩信息
   */
//   getPileInfo: function () {
//     let that = this
//     let pileCode = that.data.inputCode.replace(/[^0-9]/ig, "")
//     lbbService.getPileDetailInfo({
//       hid: parseInt(pileCode)
//     }, function (res) {
//       let gMac = ''
//       let gHid = ''
//       if(res.categoryId == 18 || res.categoryId == 25 || res.gatewayMac) {
//         let index = that.data.pileBtns.indexOf('gatewayEqu')
//         if(index == -1) {
//           that.data.pileBtns.push('gatewayEqu')
//         }        
//         gMac = res.gatewayMac ? res.gatewayMac : res.macId
//         gHid = res.gatewayHid ? res.gatewayHid : res.pileCode.replace('Z','')
//       }
//       console.log("获取桩详情-->", that.data.pileBtns, gMac, gHid)
//       that.setData({
//         pileInfo: res,
//         equipInfo: {},
//         pileBtns: that.data.pileBtns,
//         gatewayMac: gMac,
//         gatewayHid: gHid
//       })
//     })
//   },

    // 生成二维码
    createQrcode() {
        var that = this;
        const query = wx.createSelectorQuery()
        query.select('#qrcode')
        .fields({
            node: true,
            size: true
        })
        .exec((res) => {
            var canvas = res[0].node
    
            // 调用方法drawQrcode生成二维码
            qrcode.default({
            canvas: canvas,
            canvasId: 'qrcode',
            width: 300,
            padding: 10,
            background: '#ffffff',
            foreground: '#000000',
            text: that.data.qrCodeLink,
            })
    
            // 获取临时路径（得到之后，想干嘛就干嘛了）
            wx.canvasToTempFilePath({
            canvasId: 'qrcode',
            canvas: canvas,
            x: 0,
            y: 0,
            width: 300,
            height: 300,
            destWidth: 300,
            destHeight: 300,
            success(res) {
                // console.log('二维码临时路径：', res.tempFilePath)
                that.setData({
                qrcodePath: res.tempFilePath
                })
                console.log('二维码临时路径：', that.data.qrcodePath)
            },
            fail(res) {
                console.error(res)
            }
            })
        })
    }
})